#include <memory>
#include <sys/wait.h>
#include <functional>
#include "socket.hpp"
#include "inetaddr.hpp"
// TcpServer 通信
// Protocol IO
using io_service_t = std::function<void(std::shared_ptr<Socket> sock, InetAddr &addr)>;
class TcpServer
{
public:
    TcpServer(uint16_t port, io_service_t io) : _listenfd(std::make_unique<TcpSocket>()), _port(port), _running(false), _ioservice(io)
    {
        _listenfd->CreateTcpSocket(port);
    }
    ~TcpServer() {}
    void Start()
    {
        _running = true;
        while (_running)
        {
            InetAddr peer;
            // int fd = _sock->AcceptOrDie(&peer);
            // if(fd < 0)
            // {
            //     LOG(Level::WARNING) << "accept error";
            //     continue;
            // }
            auto sock = _listenfd->AcceptOrDie(&peer);
            // 多进程
            pid_t id = fork();
            if (id < 0)
            {
                LOG(Level::FATAL) << "fork error";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                _listenfd->Close();
                if (fork() == 0)
                {
                    // 孙子进程执行
                    _ioservice(sock, peer);
                }
                exit(OK);
            }
            else
            {
                sock->Close();
                waitpid(id, nullptr, 0);
            }
        }
        _running = false;
    }

private:
    std::unique_ptr<Socket> _listenfd;
    uint16_t _port;
    bool _running;
    io_service_t _ioservice;
};